#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Xml.Linq;

using Ionic.Zip;

using octalforty.Componento.ComponentModel.Tracing;
using octalforty.Componento.NuGet;
using octalforty.Componento.Shared.SemanticModel;

namespace octalforty.Componento.ComponentModel.Installation
{
    /// <summary>
    /// Represents an abstraction for retrieving component manifests from various locations.
    /// </summary>
    public interface IComponentManifestProvider
    {
        /// <summary>
        /// Verifies whether current <see cref="IComponentManifestProvider"/> can retrieve manifest from <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        bool CanProvideManifestFrom(Uri uri);

        /// <summary>
        /// Retrieves <see cref="ComponentManifest"/> from <paramref name="uri"/> for package <paramref name="componentName"/> with
        /// version requirement <paramref name="versionSpecification"/>.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="componentName"></param>
        /// <param name="versionSpecification"></param>
        /// <returns></returns>
        ComponentManifest GetComponentManifest(string componentName, Uri uri, VersionSpecification versionSpecification);
    }

    [ComponentManifestProvider]
    public class NuGetManifestProvider : IComponentManifestProvider
    {
        public bool CanProvideManifestFrom(Uri uri)
        {
            return uri.Scheme.ToLowerInvariant() == "nuget";
        }

        public ComponentManifest GetComponentManifest(string componentName, Uri uri, VersionSpecification versionSpecification)
        {
            var repositoryUri = new UriBuilder(uri) { Scheme = "http" };
            if(!repositoryUri.Path.EndsWith("/"))
                repositoryUri.Path += "/";

            var atom = XNamespace.Get("http://www.w3.org/2005/Atom");
            var m = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            var d = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices");

            //
            // Sure, Microsoft really needed DataServiceVersion to be 2.0, thus requiring
            // everybody to upgrade to .NET 4.0. Burn in hell.
            var xdocument = XDocument.Load(new Uri(repositoryUri.Uri, "Packages").ToString());
            var packages = xdocument.Element(atom + "feed").Elements(atom + "entry").
                Where(e => string.Compare(e.Element(m + "properties").Element(d + "Id").Value, componentName, true) == 0);

            var package =
                packages.FirstOrDefault(
                    e =>
                    versionSpecification.Matches(new Version(e.Element(m + "properties").Element(d + "Version").Value)));

            
            var resourceUri = new UriBuilder(package.Element(atom + "content").Attribute("src").Value) { Scheme = "nupkg" }.Uri;

            //
            // Dependencies are stored in a fucked-up way: Argotic.Common:2008.0.2.0|Argotic.Extensions:2008.0.2.0
            var deps = package.Element(m + "properties").Element(d + "Dependencies").Value;
            var dependencies = string.IsNullOrEmpty(deps) ?
                null :
                deps.Split('|').
                    Select(dep => new ComponentReference(dep.Split(':')[0].ToLowerInvariant(), new Version(dep.Split(':')[1]), uri));

            var manifest = new ComponentManifest(
                new ComponentDescriptor(
                    package.Element(m + "properties").Element(d + "Id").Value.ToLowerInvariant(),
                    new Version(package.Element(m + "properties").Element(d + "Version").Value),
                    new Uri(package.Element(atom + "id").Value),
                    null, null), 
                    new[] { new Resource(resourceUri) }, 
                    new[] { 
                        new PathMapping(new CliEnvironment(CliType.NetFramework, new Version(2, 0)), IsaType.Cil) {
                            { PathMappingTarget.Binaries, "~/lib/net20" },
                            { PathMappingTarget.Binaries, "~/lib/net35" }
                        },
                        new PathMapping(new CliEnvironment(CliType.NetFramework, new Version(3, 5)), IsaType.Cil) {
                            { PathMappingTarget.Binaries, "~/lib/net20" },
                            { PathMappingTarget.Binaries, "~/lib/net35" }
                        }
                    }, 
                    dependencies);

            return manifest;

            //return new ComponentManifest(package.Title, new Version(package.Version), new Resource[] { });
        }
    }

    [ResourceProvider]
    public class NupgkResourceProvider : HttpFileResourceProvider
    {
        [ImportingConstructor()]
        public NupgkResourceProvider(ITraceManagerService traceManager) :
            base(traceManager)
        {
        }

        public override bool CanProvideResourcesFrom(Uri uri)
        {
            return uri.Scheme.ToLowerInvariant() == "nupkg";
        }

        protected override octalforty.Componento.ComponentModel.Installation.Web.IHttpRequest CreateHttpRequest(Uri uri)
        {
            return base.CreateHttpRequest(new UriBuilder(uri) { Scheme = "http"}.Uri);
        }
    }

    [ResourceInstaller(Priority = 90)]
    public class NupkgResourceInstaller : IResourceInstaller
    {
        #region Public Properties
        public ITrace Trace
        { get; set; }

        public ITraceManagerService TraceManager
        { get; set; }

        [Import()]
        public IPathBuilderService PathBuilder 
        { get; set; }
        #endregion


        [ImportingConstructor()]
        public NupkgResourceInstaller(ITraceManagerService traceManager)
        {
            TraceManager = traceManager;
            Trace = TraceManager.GetTrace(GetType().Name);
        }

        public bool CanInstallResourceFrom(Uri resourceUri)
        {
            return Path.GetExtension(resourceUri.LocalPath).ToLowerInvariant() == ".nupkg";
        }

        public void InstallResource(Uri resourceUri, string destinationPathRoot, PathMapping pathMapping)
        {
            using(var zipFile = new ZipFile(resourceUri.LocalPath))
            {
                if(pathMapping == null)
                {
                    #region Tracing
                    Trace.Verbose("Extracting all files to '{0}'", destinationPathRoot);
                    #endregion

                    zipFile.ExtractAll(destinationPathRoot, ExtractExistingFileAction.OverwriteSilently);
                } // f
                else
                {
                    foreach(var zipEntry in zipFile.Entries)
                    {
                        foreach(var mappingTarget in pathMapping)
                        {
                            var sub = pathMapping[mappingTarget].Substring(2);

                            var zipFileName = zipEntry.FileName.ToLowerInvariant();
                            if(!zipEntry.IsDirectory && (sub.Length == 0 || (zipFileName.StartsWith(sub.ToLowerInvariant()) && zipFileName.Length > sub.Length)))
                            {
                                string dest = PathBuilder.BuildPath(destinationPathRoot, mappingTarget);
                                string sfp = zipEntry.FileName.Substring((sub.Length == 0 ? -1 : sub.Length) + 1);

                                #region Tracing
                                Trace.Verbose("Extracting '{0}' to '{1}'", sfp, dest);
                                #endregion

                                string fullPath = Path.Combine(dest, sfp);

                                string dir = Path.GetDirectoryName(fullPath);

                                if(!Directory.Exists(dir))
                                    Directory.CreateDirectory(dir);

                                using(FileStream fs = File.Open(fullPath, FileMode.Create))
                                    zipEntry.Extract(fs);
                            } // if
                        } // foreach
                        
                    } // foreach
                } // else
            } // using
        }
    }
}